package edu.pku.sei.modeler.neditor.part;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.gef.editparts.AbstractTreeEditPart;
import org.eclipse.ui.views.properties.IPropertySource;

import edu.pku.sei.gefcommon.descriptor.core.PropertyDescriptorAdapter;
import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.modeler.model.notation.core.ShapeConstance;
import edu.pku.sei.modeler.model.notation.core.ShapeNode;
import edu.pku.sei.modeler.model.notation.shape.Shape;
import edu.pku.sei.modeler.neditor.model.Diagram;

public class ShapeTreeEditPart extends AbstractTreeEditPart implements
PropertyChangeListener{
    public void activate() {
        super.activate();
        ((MetaModelElement) getModel()).addPropertyChangeListener(this);
    }

    public void deactivate() {
        super.deactivate();
        ((MetaModelElement) getModel()).removePropertyChangeListener(this);
    }
    public Object getAdapter(Class key) {
		if (IPropertySource.class == key) {
			Object model = getModel();
			if(model instanceof ShapeNode){
				return new PropertyDescriptorAdapter((MetaModelElement)model);
			}
		}
		return super.getAdapter(key);
	}    
	public void propertyChange(PropertyChangeEvent evt) {
		String type = evt.getPropertyName();
		if(type==ShapeConstance.REFRESH_ALL){
			this.refreshStructure();
			this.refreshVisuals();
		} else if(type==ShapeConstance.REFRESH_VIEW){
			this.refreshVisuals();
		}
	}
	
	public void refreshStructure(){
		this.refreshChildren();
	}
	public void refreshVisuals(){
		MetaModelElement model = (MetaModelElement)this.getModel();
		String type = model.getClass().getSimpleName();
		int id = model.getElementID();
		this.setWidgetText("id="+id+":"+type);
	}
	protected List getModelChildren() {
		if (getModel() instanceof Diagram) {
			List children = new ArrayList();
			children.addAll(((Diagram) getModel()).getNotation().getNotations());
			return children;
		} else {
			List children = new ArrayList();
			children.addAll(((Shape) getModel()).getSlaves());
			return children;
		}
	}
}
